package com.damagedboy.base.adminuser;

import com.damagedboy.base.po.AdminUserPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Repository
public class AdminUserDAOImpl implements IAdminUserDAO {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public List<AdminUserPO> selectByCondition(String username, String phone) {
        List<Object> params = new ArrayList<>();

        StringBuilder sb = new StringBuilder();
        sb.append("select * from base_admin_user where name <> ? ");
        params.add("admin");

        if (!StringUtils.isEmpty(username)) {
            sb.append("and name=?");
            params.add(username);
        }

        if (!StringUtils.isEmpty(phone)) {
            sb.append("and phone=?");
            params.add(phone);
        }

        return jdbcTemplate.query(sb.toString(), params.toArray(), BeanPropertyRowMapper.newInstance(AdminUserPO.class));
    }

    @Override
    public AdminUserPO getAdminUserByUserNameAndPassword(String username, String password) {
        final String sql = "select * from base_admin_user where login_name=? and password=?";

        List<AdminUserPO> query = jdbcTemplate.query(sql, new Object[]{username, password},
                BeanPropertyRowMapper.newInstance(AdminUserPO.class));
        if (query.isEmpty()) {
            return null;
        } else {
            return query.get(0);
        }
    }
}
